Unit tests should never(❗) call the internet
I’ve written a lot of unit tests with Pytest over the years and I’ve been on several Python projects where unit tests accidentally end up calling the internet.
Sometimes it’s harmless or just slows the test runner down a little, but sometimes it causes instability and can either run up a bill on a service you pay for or accidentally result in a denial of service (hopefully only on yourself).
Here is a quick way to add safeguards so that if a unit test DOES call the internet, it’s intentional and something your team has decided it wants to happen.
conftest.py
|
|
pytest.ini
|
|
And here is an example of skipping this rule for a test
tests.py
|
|
Wait?!?! Why would this test be calling the internet?!?!
I was caught off guard by this as well.
The test above generates an HTML email that would get sent to the user. In testing mode, the email isn’t sent, but has it’s contents logged so we can inspect it with caplog and verify that the email we generated is valid and works.
All good, nothing leaving our system.
BUT. . .when we generate the HTML for that email, there are asset requests for CSS/etc that do go out to the internet.
So should we mock or prevent that from happening? Skip HTML generation? I’m not worrying about it for this one case at the moment, but knowing that this test calls out and being forced to make an intentional decision is very valuable in my mind.